package com.llap.exp190929.service;

import com.llap.exp190929.entity.District;
import com.llap.exp190929.repository.DistrictRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
@Slf4j
public class DistrictService {
    private DistrictRepository districtRepository;

    public District findDistrict(int id) {
        return districtRepository.findById(id).orElse(null);
    }

    public Page<District> findDistricts(int page, int pageSize) {
        return districtRepository.findAll(PageRequest.of(page - 1, pageSize));
    }

    @Transactional
    public District addDistrict(District district) {
        if (district.getId() != null) return null;
        return districtRepository.save(district);
    }

    @Transactional
    public District updateDistrict(District district) {
        if (district.getId() == null) return null;
        return districtRepository.save(district);
    }

    @Transactional
    public void deleteDistrict(int id) {
        districtRepository.deleteById(id);
    }
}
